import ProCard from '@ant-design/pro-card';
import React, { useEffect, useState } from 'react';
import Title from './components/Title';
import { getDevApps } from './utils/api';
import { invoke, path } from '@tauri-apps/api';
import { Link } from 'react-router-dom';
import { listen } from '@tauri-apps/api/event';
import { Tag, Typography } from 'antd';
import { useLocalStorageState } from 'ahooks';

const { Paragraph } = Typography;

const Home: React.FC<any> = () => {
  const [apps, setApps] = useState<any[]>([]);
  const [devApps, setDevApps] = useState<any[]>([]);
  const [values, _] = useLocalStorageState<any>('settings');
  useEffect(() => {
    listen('reply', (res) => {
      console.log(res);
    });
    listen('message', (res) => {
      console.log(res);
    });
    path.resourceDir().then((res) => {
      console.log('resourceDir: ', res);
    });
  }, []);

  useEffect(() => {
    invoke('get_all_extensions').then((extensions) => {
      setApps(extensions as any[]);
      console.log('get_all_extensions', extensions);
    });

    if (values?.devApps) {
      getDevApps(values?.devApps).then((devApps) => {
        console.log('devApps: ', devApps);
        setDevApps(devApps.map((item) => ({ ...item, isDev: true })));
      });
    }
  }, []);

  return (
    <ProCard
      className="apps"
      gutter={[16, 16]}
      wrap
      title={<Title>应用中心</Title>}
      bodyStyle={{ margin: 0 }}
    >
      {[...devApps, ...apps].map(
        ({ title, path, main, name, dev, isDev, ...item }: any) => {
          let url = `https://${name}.extension/${main}`;
          if (isDev && dev?.url) {
            url = dev?.url;
          }
          return (
            <ProCard
              key={url}
              colSpan={{ xs: 24, sm: 12, md: 12, lg: 12, xl: 12 }}
              bordered
              bodyStyle={{
                paddingTop: 0,
                paddingBottom: 0,
                minHeight: 60,
                display: 'flex',
                alignItems: 'center',
              }}
              title={
                <Title level={3}>
                  <Tag color="#5BD8A6">PY</Tag>
                  {title}
                </Title>
              }
              extra={
                <Link to="/__" state={{ url, title }}>
                  进入
                </Link>
              }
            >
              <Paragraph
                style={{ marginBottom: 0 }}
                ellipsis={{
                  rows: 2,
                  tooltip: item.description,
                }}
              >
                {item.description}
              </Paragraph>
            </ProCard>
          );
        },
      )}
    </ProCard>
  );
};

export default Home;
